<template>
  <div class="tech01">
    <h2>name = {{ name }} age = {{ age }}</h2>
    <h2>person = {{ person }}</h2>
    <h2>person2 = {{ person2 }}</h2>
    person2 = <input v-model="person2" type="text" /> {{ person2 }}
    <div>
      <h2>zhaoliu = {{ zhaoliu }}</h2>
      <span v-show="zhaoliu.name">zhaoliu.name = {{ zhaoliu.name }}</span><br>
      <span v-show="zhaoliu.age"> zhaoliu.age = {{ zhaoliu.age }}</span><br>
      <span v-show="zhaoliu.sex">zhaoliu.sex = {{ zhaoliu.sex }}</span><br>
    </div>
    <button @click="addInfo">添加</button>
    <button @click="changeInfo">改变</button>
    <button @click="deleteInfo">删除</button>
  </div>
</template>

<script >

import { ref, reactive, customRef } from "vue";

export default {
  name: "TechRef",
  setup() {

    //#region
    let name = ref('张三')
    // let name = '张三'
    let age = ref(18)

    let person = ref({
      name: "王五",
      age: 20
    })

    let zhaoliu = reactive({
      name: "赵六",
      age: 20
    })

    function myRef(value) {
      return customRef((track, trigger) => {
        return {
          get() {
            console.log("myRef get", value)
            // track(); / 通知Vue追踪value的变化【提前与get商量一下，让他认为这个value是有用的】
            return value
          },
          set(newValue) {
            console.log("myRef set", this.value, `${newValue}`)
            // value = newValue;
            // trigger(); // 通知Vue去重新解析模版
            setTimeout(() => {
              value = newValue;
              trigger(); // 通知Vue去重新解析模版
            }, 2000);
          }
        }
      });
    }

    let person2 = myRef("hello");

    function changeInfo() {
      name.value = '里斯'
      console.log(name)
      person.value.age = 30
      console.log(person)

      zhaoliu.age = 30
      console.log(zhaoliu)
    }

    function addInfo() {
      zhaoliu.sex = '男'
    }

    function deleteInfo() {
      delete zhaoliu.sex
    }

    return {
      name,
      age,
      changeInfo,
      person,
      person2,
      zhaoliu,
      addInfo,
      deleteInfo
    }
  }
}

</script>

<style scoped>
@media (min-width: 1024px) {
  .tech01 {
    min-height: 100vh;
    align-items: center;
  }
}
</style>
